<template>
  <view class="content">
    <u-navbar :background="navObj" :is-back="false">
      <mSearch
          ref="mSearch"
          class="mSearch-input-box"
          @clickLeft="back"
          :mode="2"
          :placeholder="defaultKeyword"
          @search="doSearch(false)"
          @confirm="doSearch(false)"
          @SwitchType="doSearchSwitch()"
          v-model="keyword"
          :isFocusVal="!isShowSeachHouses"
      ></mSearch>
    </u-navbar>

    <view class="search-keyword" v-if="!isShowSeachHouses">
      <scroll-view class="keyword-list-box" v-show="isShowKeywordList" scroll-y>
        <block v-for="(row, index) in keywordList" :key="index">
          <view class="keyword-entry" hover-class="keyword-entry-tap">
            <view class="keyword-text" @tap.stop="doSearch(keywordList[index].words)"><rich-text :nodes="row.words"></rich-text></view>
          </view>
        </block>
      </scroll-view>
      <div class="keyword-box" v-show="!isShowKeywordList">
        <view class="keyword-block add1">
          <view class="keyword-list-header"><view class="u-tips">热门搜索</view></view>
          <view class="keyword keywordBox">
            <view class="wes" v-for="(keyword, index) in hotKeywordList" @tap="doSearch(keyword)" :key="index">{{ keyword }}</view>
          </view>
        </view>
        <view class="keyword-block" v-if="oldKeywordList.length > 0">
          <view class="keyword-list-header"><view class="u-tips">搜索历史</view></view>
          <div class="oldKeyList">
            <div class="oldKeyItem" v-for="(keyword, index) in oldKeywordList" :key="index" @click="doSearch(keyword)">
              <span>{{ keyword }}</span>
            </div>
            <div @click="showMore" v-if="oldKeywordIndex > loadIndex" class="oldKeyItem">展示更多</div>
          </div>
        </view>
        <div class="clear mp-iphonex-bottom" @tap="oldDelete">清空搜索历史</div>
      </div>
    </view>
    <!-- 搜索栏 -->
    <view class="houses-content" v-if="isShowSeachHouses">
      <!-- 筛选栏 -->
      <view class="dadropdown-box">
        <DaDropdownVue2
            :dropdownMenu="dropdownMenuList"
            @confirm="handleConfirm"
            @close="handleClose"
            @open="handleOpen"
        ></DaDropdownVue2>
      </view>
      <!-- 房源展示 -->
      <div>
        <scroll-view
            :style="{ height: housesHeight }"
            enableBackToTop="true"
            lower-threshold="250"
            @scrolltolower="loadmore()"
            scroll-with-animation
            scroll-y
            class="scoll-page"
        >
          <fangTemplate style="width: 100%;" :res="housesList" :storeName="false"  />
          <uni-load-more :status="loadingType" @loadmore="loadmore()"></uni-load-more>
        </scroll-view>
      </div>
    </view>

    <div class="empty" v-if="empty">
      <view><image style="width: 320rpx; height: 240rpx" src="/static/nodata.png"></image></view>
      <view>
        <p>没有找到相关的房源信息</p>
        <p>请换一个关键词试试吧</p>
      </view>
    </div>
    <u-back-top :scroll-top="scrollTop"></u-back-top>
  </view>
</template>

<script>
import { getHousesList, findHouseRoomList } from "@/api/house";
import fangTemplate from '@/components/m-goods-list/fangList'
import { getHotKeywords } from '@/api/home.js';
import mSearch from '@/components/m-search-revision/m-search-revision.vue';
import storage from '@/utils/storage';
import DaDropdownVue2 from '@/components/da-dropdown-vue2/index.vue'
import {getAddressItemByCode} from '@/api/address'
export default {
  data() {
    return {
      dropdownMenuList: [
        {
          title: '区域',
          type: 'cell',
          prop: 'god1',
          showAll: true,
          showIcon: true,
          value: '', // 默认内容2
          options: uni.getStorageSync('addressData'),
        },
        {
          title: '售价',
          type: 'cell',
          prop: 'god1',
          showAll: true,
          showIcon: true,
          value: '', // 默认内容2
          options: [
            { label: '3000元以下', value: '1' },
            { label: '3000 - 5000元', value: '2' },
            { label: '5000 - 6000元', value: '3' },
            { label: '6000 - 7000元', value: '4' },
            { label: '7000 - 8000元', value: '5' },
            { label: '8000 - 9000元', value: '6' },
            { label: '9000 - 10000元', value: '7' },
            { label: '10000元以上', value: '8' },
          ],
        },
        {
          title: '排序',
          type: 'cell',
          prop: 'god1',
          showAll: true,
          showIcon: true,
          value: '2', // 默认内容2
          options: [
            { label: '价格升序', value: '2' },
            { label: '价格降序', value: '3' },
            { label: '时间升序', value: '2' },
            { label: '时间降序', value: '3' },
          ],
        },

        {
          title: '日期',
          type: 'daterange',
          prop: 'god6',
          // 默认选中 2022-01-01到2022-02-01
          value: { start: '', end: '' },
        },
      ],
      empty: false,
      scrollTop: 0,
      loadIndex: 10,
      oldKeywordIndex: 0,
      selectedWay: {
        brand: [],
        categoryId: [],
        prop: []
      },
      navObj: {
        background: '#fff'
      },
      housesHeight: '',
      defaultKeyword: '',
      keyword: '',
      oldKeywordList: [],
      hotKeywordList: [],
      keywordList: [],
      housesList: [],
      loadingType: 'more', // 加载更多状态
      isShowSeachHouses: false,
      isShowKeywordList: false,
      sortData: '',
      isSWitch: false,
      params: {
        state:2,
        villageCity:uni.getStorageSync("address").district,
        pageNumber: 1,
        pageSize: 10,
        keyword: '',
        area:  '',
        avgPrice: '',
        sort: '',
        startDate2: '',
        endDate: '',
      },
      minPrice: '',
      maxPrice: '',
      sortParams: {
        pageNumber: 1,
        pageSize: 10,
        categoryId: ''
      },
      routerVal: ''
    };
  },

  onPageScroll(e) {
    this.scrollTop = e.scrollTop;
  },

  onLoad(val) {
    this.init();
    this.routerVal = val;

    if (this.routerVal.category) {
      this.params.categoryId = this.routerVal.category;
      this.sortParams.categoryId = this.routerVal.category;
      this.isShowSeachHouses = true;
      this.$nextTick(() => {
        this.$refs.mSearch.isShowSeachHouses = true;
      });
    }
    if (this.routerVal.keyword) {
      this.params.keyword = this.routerVal.keyword;
      this.isShowSeachHouses = true;
    }
    if (this.routerVal.storeId) {
      this.params.storeId = this.routerVal.storeId;
      this.isShowSeachHouses = true;
    }
    if (this.routerVal.promotionType) {
      this.params.promotionType = this.routerVal.promotionType;
      this.isShowSeachHouses = true;
    }
    if (this.routerVal.promotionsId) {
      this.params.promotionsId = this.routerVal.promotionsId;
      this.isShowSeachHouses = true;
    }

    var address=uni.getStorageSync('address');
    if(""!=address){
      getAddressItemByCode(address.adcode).then(res => {
        // this.regionList = res.data.data;

        if(""==uni.getStorageSync('addressData')){

          uni.setStorageSync('addressData',res.data.data)
          //刷新此页面
          uni.reLaunch({
            url: '/pages/house/searchHouse'
          });
        }else {
          uni.setStorageSync('addressData',res.data.data)

        }
      });
    }
  },

  components: {
    mSearch,
    fangTemplate,
    DaDropdownVue2
  },

  watch: {
    keyword(val) {
      this.defaultKeyword = val || '请输入搜索房源';
    },

  },

  onReachBottom() {
    this.params.pageNumber++;
    this.loadData();
  },

  mounted() {
    const { windowWidth, windowHeight } = uni.getSystemInfoSync();
    let topHeight = 0;
    let navHeight = 0;

    uni.getSystemInfo({
      success: (res) => {
        uni.createSelectorQuery().select('.u-navbar').boundingClientRect((data) => {
          if (data && data.height) {
            topHeight = data.height;
          }
        }).exec();
        uni.createSelectorQuery().select('.navbar').boundingClientRect((data) => {
          if (data && data.height) {
            navHeight = data.height;
          }
        }).exec();
      }
    });

    this.housesHeight = windowHeight - navHeight - topHeight;
    // #ifdef APP-PLUS
    this.housesHeight = this.housesHeight - 100;
    // #endif
    this.housesHeight += 'px';
  },

  methods: {
    handleConfirm(v, selectedValue) {
      console.log('handleConfirm ==>', v, selectedValue)
    },
    handleClose(v, callbackMenuList) {
      if(v==0){
        this.params.area=callbackMenuList[0].activeTitle;
      }else if(v==1){
        this.params.avgPrice=callbackMenuList[1].activeTitle;
      }else if(v==2){
        this.params.sort=callbackMenuList[2].activeTitle;
      }else if(v==3){

        if(null!=callbackMenuList[3].value){
          this.params.startDate2=callbackMenuList[3].value.start;
          this.params.endDate=callbackMenuList[3].value.end
        }else{
          this.params.startDate2=null
          this.params.endDate=null
        }

      }
      this.params.pageNumber = 1;
      //this.hasMore = true;
      this.housesList=[]
      this.loadData();
      console.log('handleClose ==>', v, callbackMenuList)
    },
    handleOpen(v) {
      console.log('handleOpen ==>', v)
    },
    showMore() {
      this.loadOldKeyword(this.oldKeywordIndex);
    },

    sortConfim() {
      this.params.brandId = this.selectedWay.brand.filter(item => item.__selected).map(item => item.value).join('@');
      this.params.categoryId = this.selectedWay.categoryId[0]?.value || '';
      this.params.prop = this.selectedWay.prop.filter(item => item.__selected).map(item => `${item.parent}_${item.title}`).join('@');
      this.params.price = this.minPrice || this.maxPrice ? `${this.minPrice}_${this.maxPrice}` : 0;

      this.housesList = [];
      this.params.pageNumber = 1;
      this.sortParams = { ...this.params };
      this.loadData();
    },

    repick() {
      this.sortParams = {
        pageNumber: 1,
        pageSize: 10,
        categoryId: this.routerVal.category || ''
      };
      this.minPrice = '';
      this.maxPrice = '';
      this.params = {
        pageNumber: 1,
        pageSize: 10,
        categoryId: this.routerVal.category || ''
      };
      this.housesList = [];
      this.loadData();
    },

    handleSort(val, index, type, parent) {
      if (type === 'prop') {
        val.parent = parent.key;
      }
      if (type === 'categoryId') {
        this.sortData.categories.forEach(item => {
          item.__selected = false;
        });
        val.__selected = true;
      } else {
        val.__selected = !val.__selected;
      }
      this.selectedWay[type] = this.selectedWay[type].filter(item => item !== val);
      if (val.__selected) {
        this.selectedWay[type].push(val);
      }
    },

    init() {
      this.loadOldKeyword(this.loadIndex);
      this.loadHotKeyword();
    },

    back() {
      uni.navigateBack({
        delta: 1
      });
    },

    loadmore() {
      this.params.pageNumber++;
      this.loadData();
    },

    loadDefaultKeyword() {
      this.defaultKeyword = this.hotKeywordList[0] || '请输入搜索房源';
    },

    loadOldKeyword(index) {
      this.oldKeywordList = [];
      uni.getStorage({
        key: 'OldKeys',
        success: res => {
          const OldKeys = JSON.parse(res.data);
          this.oldKeywordIndex = OldKeys.length;
          this.oldKeywordList = OldKeys.slice(0, index);
        }
      });
    },

    async loadHotKeyword() {
      this.hotKeywordList = [];
      const hotWords = storage.getHotWords();
      if (!hotWords.time || hotWords.time <= new Date().getTime() / 1000) {
        const res = await getHotKeywords(10);
        const keywords = res.data.result;
        this.hotKeywordList = keywords;
        const hotData = {
          time: new Date().getTime() / 1000 + 30 * 5,
          keywords
        };
        storage.setHotWords(hotData);
      } else {
        this.hotKeywordList = hotWords.keywords;
      }
      this.loadDefaultKeyword();
    },

    async loadData(type = '') {
      this.loadingType = 'loading';
      if (type === 'refresh') {
        this.housesList = [];
      }

      const housesList = await findHouseRoomList(this.params);

      if (housesList.data.rows.length < 10) {
        this.loadingType = 'noMore';
        this.empty = true;
      } else {
        this.empty = false;
      }
      this.housesList.push(...housesList.data.rows);
      if (this.$store.state.isShowToast) {
        uni.hideLoading();
      }
    },

    oldDelete() {
      uni.showModal({
        content: '确定清除历史搜索记录？',
        success: res => {
          if (res.confirm) {
            this.oldKeywordList = [];
            uni.removeStorage({
              key: 'OldKeys'
            });
          }
        }
      });
    },

    doSearchSwitch() {
      this.isSWitch = !this.isSWitch;
      this.isShowSeachHouses = true;
      this.params.pageNumber = 1;
      this.params.pageSize = 10;
      this.loadData('refresh');
    },

    doSearch(keyword) {
      keyword = keyword === false ? this.keyword : keyword;
      if (!keyword) {
        keyword = this.hotKeywordList[0] || '';
      }
      this.keyword = keyword;
      this.saveKeyword(keyword);
      this.isShowSeachHouses = true;
      this.$refs.mSearch.isShowSeachHouses = true;
      this.$refs.mSearch.inputVal = keyword;
      this.params.keyword = keyword;
      this.params.pageNumber = 1;
      this.sortParams.keyword = keyword;
      this.loadData('refresh');
    },

    saveKeyword(keyword) {
      if (!keyword) return;
      uni.getStorage({
        key: 'OldKeys',
        success: res => {
          let OldKeys = JSON.parse(res.data);
          const findIndex = OldKeys.indexOf(keyword);
          if (findIndex > -1) {
            OldKeys.splice(findIndex, 1);
          }
          OldKeys.unshift(keyword);
          if (OldKeys.length > 10) {
            OldKeys.pop();
          }
          uni.setStorage({
            key: 'OldKeys',
            data: JSON.stringify(OldKeys)
          });
          this.oldKeywordList = OldKeys;
        },
        fail: () => {
          const OldKeys = [keyword];
          uni.setStorage({
            key: 'OldKeys',
            data: JSON.stringify(OldKeys)
          });
          this.oldKeywordList = OldKeys;
        }
      });
    }
  }
};
</script>
<style lang="scss" scoped>
@import './search.scss';
</style>